package com.sinodata.bsm.cicp.finder.sco;

/**
 * <p>Title: </p>
 * <p>
 * sco主机的发现程序的父类
 * </p>
 * <p>Copyright: Copyright (c) 2004</p>
 * <p>Company: </p>
 * @author liuxz
 * @version 1.0
 */
import java.io.BufferedReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;

import com.sinodata.bsm.cicp.finder.Finder;
import com.sinodata.bsm.cicp.util.CommandReader;

public abstract class ScoFinder extends Finder {
    private static final Logger logger = Logger.getLogger(ScoFinder.class);
    private static final String HOSTNAME_CMDSTR = "hostname";
    private String HOSTNAME = "";

    /*SCO发现程序的命令运行时间间隔*/
    protected static final int SCO_FINDER_DEFAULT_TIMEOUT = 5;

    public ScoFinder() {

    }

    /**
     * 获取主机名.在SCO资源发现时,将设置资源描述为:主机名_资源描述
     */
    final String getHostName(String ip) {
        if (!HOSTNAME.equals("")) {
            return HOSTNAME;
        }
        BufferedReader reader = null;
        String strLine = null;
        try {
            reader = CommandReader.getReader(ip, HOSTNAME_CMDSTR, 0, 0);
            while ((strLine = reader.readLine()) != null) {
                if (strLine.trim() != null && strLine.trim().length() > 0) {
                    HOSTNAME = strLine.trim();
                    break;
                }
            }

        } catch (IOException e) {
            logger.error("failed to get hostname ", e);
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    logger.error("failed to close reader", e);
                }
            }
        }
        return HOSTNAME;
    }

    /**
     * 获取cmdStr的运行结果,以List of String形式返回
     *
     * @param cmdStr
     * @return
     * @throws IOException 
     */
    public List<String> getResultStrFromCommand(String cmdStr, String ip) throws IOException {
        List<String> retList = new ArrayList<String>();
        String strLine = null;
        BufferedReader reader = CommandReader.getReader(ip, cmdStr, 0, 0);
        while ((strLine = reader.readLine()) != null) {
            retList.add(strLine);
        }
        if (reader != null) {
            try {
                reader.close();
            } catch (Throwable t) {
                logger.error("failed to close reader", t);
            }
        }
        return retList;
    }
}
